package ua.kiev.tosik.price.modules.search.database;

import org.apache.log4j.Logger;
import ua.kiev.tosik.price.database.dao.IPricesDao;
import ua.kiev.tosik.price.models.Prices;
import ua.kiev.tosik.price.modules.search.conf.ModuleConfig;

import javax.swing.*;
import java.util.ArrayList;
import java.util.List;

public class DataLoadWorker extends SwingWorker<List<Prices>, Void> {

	private static Logger logger = Logger.getLogger("ua.kiev.tosik.price.modules.search.database");
	private List<Prices> pricesList;
	private IPricesDao pricesDao;

	public DataLoadWorker(IPricesDao pricesDao) {
		super();
		logger.debug("Initialize [Prices] DataLoadWorker");
		this.pricesDao = pricesDao;
		pricesList = new ArrayList<Prices>();
	}

	@Override
	protected List<Prices> doInBackground() throws Exception {
		if ( pricesDao != null ) {
			firePropertyChange("SEARCH_START", false, ModuleConfig.getInstance().get("search.data.loading"));
			pricesList = pricesDao.findAll();
		}
		firePropertyChange("SEARCH_DONE", false, true);
		logger.debug("Found " + pricesDao.getRecordCount() + " record(s)");
		return pricesList;
	}

	@Override
	protected void done() {
		firePropertyChange("SEARCH_OK", false, true);
		try {
			pricesList = get();
			firePropertyChange("PricesList", null, pricesList);
		} catch (Exception e) {
			logger.error(e);
		}
	}

}
